package controller;

import java.io.IOException;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entity.SearchResult;

import test.SolrHelper;

/**
 * Servlet implementation class NewsSearch
 */
@WebServlet("/tim-kiem")
public class NewsSearch extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		String key = request.getParameter("key");
		String from = request.getParameter("from");
		String to = request.getParameter("to");
		String cate = request.getParameter("cate");
		System.out.println("------------------");
		Calendar fromDate = null;
		Calendar toDate = null;
		// get date from and to.
		try {
			int day = 0;
			int month = 0;
			int year = 0;
			String[] f = from.split("-");
			if (f.length == 3) {
				day = Integer.parseInt(f[0]);
				month = Integer.parseInt(f[1]);
				year = Integer.parseInt(f[2]);
				fromDate = Calendar.getInstance();
				fromDate.set(year, month, day);
				System.out.println(fromDate.get(Calendar.DATE));
				System.out.println(fromDate.get(Calendar.MONTH));
				System.out.println(fromDate.get(Calendar.YEAR));
			}
			String[] t = to.split("-");
			if (t.length == 3) {
				day = Integer.parseInt(t[0]);
				month = Integer.parseInt(t[1]);
				year = Integer.parseInt(t[2]);
				toDate = Calendar.getInstance();
				toDate.set(year, month, day);
			}
		} catch (Exception e) {
			System.out.println("Error me no roi ! ");
			e.printStackTrace();
		}

		// search
		if (key != null && !key.equalsIgnoreCase("")) {
			key = new String(key.getBytes("8859_1"), "UTF8");
			if (cate == null)
				cate = "none";
			SearchResult re = SolrHelper.search(key, fromDate, toDate,
					cate.equalsIgnoreCase("none") ? null : cate);
			if (re != null) {
				request.setAttribute("list", re.getListNews());
				request.setAttribute("key", key);
				request.setAttribute("infor",
						"(Tìm thấy : " + re.getTotalResult()
								+ " kết quả trong : " + re.getQueryTime()
								+ " giây)");
				if (re.getListNews().size() == 0) {
					request.setAttribute(
							"msg",
							"(Từ khoá bạn tìm kiếm quá hot, nên không có kết quả nào. Vui lòng tìm kiếm với từ khoá khác)");
				}
				request.getRequestDispatcher("/search_result.jsp").forward(
						request, response);
			}

		} else {
			request.getRequestDispatcher("/search_result.jsp").forward(request,
					response);
		}

	}

}
